<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :inline="true"
    v-if="formBox"
    :rules="rules"
    class="form1-ruleForm"
    status-icon
  >
    <div>
      <FormTitle>基础</FormTitle>
      <el-row style="margin-top: 15px">
        <el-col :span="8">
          <el-form-item prop="name">
            <template #label>
              <div style="white-space: normal">分类</div>
            </template>
            <el-select
              v-model="ruleForm.drugCategory"
              :disabled="dataType.dataType == 1"
              filterable
              clearable
              style="width: 100%"
              @change="selectRules"
              placeholder="分类"
            >
              <el-option
                v-for="item in btnList"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="drugName">
            <template #label>
              <div style="white-space: normal">
                {{ ruleForm.drugCategory == '3' ? '耗材名' : '药品名' }}
              </div>
            </template>
            <el-input v-model="ruleForm.drugName" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="genericName">
            <template #label>
              <div style="white-space: normal">通用名</div>
            </template>
            <el-input
              v-model="ruleForm.genericName"
              placeholder="通用名"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '3'"
        >
          <el-form-item prop="approvalNumber">
            <template #label>
              <div style="white-space: normal" placeholder="批准文号">
                批准文号
              </div>
            </template>
            <el-input v-model="ruleForm.approvalNumber" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="ruleForm.drugCategory == '1'">
          <el-form-item prop="drugIngr">
            <template #label>
              <div style="white-space: normal">成分</div>
            </template>
            <el-select
              v-model="drugIngrList"
              clearable
              filterable
              multiple
              style="width: 100%"
              placeholder="成分"
            >
              <el-option
                v-for="item in DRUG_INGR"
                :key="item.itemCode"
                :label="item.itemName"
                :value="item.itemCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '2'"
        >
          <el-form-item prop="dosageForm">
            <template #label>
              <div style="white-space: normal">剂型</div>
            </template>
            <el-select
              v-model="ruleForm.dosageForm"
              filterable
              clearable
              style="width: 100%"
              placeholder="剂型"
            >
              <el-option
                v-for="item in DosageFormEnum"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="mfrId">
            <template #label>
              <div style="white-space: normal">生产厂家</div>
            </template>
            <el-select
              v-model="ruleForm.mfrId"
              filterable
              clearable
              style="width: 100%"
              placeholder="生产厂家"
            >
              <el-option
                v-for="item in mfrList"
                :key="item.mfrId"
                :label="item.mfrName"
                :value="item.mfrId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <div v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '3'" style="position: relative;">
      <FormTitle>规格</FormTitle>
      <el-row style="margin-top: 15px">
        <el-col :span="8" v-if="ruleForm.drugCategory == '1'">
          <el-form-item prop="drugDosage">
            <template #label>
              <div style="white-space: normal">剂量（成分含量）</div>
            </template>
            <el-input
              v-model="ruleForm.drugDosage"
              placeholder="剂量"
              class="inputpadding0"
              style="width: 100%"
            >
              <template #append>
                <UnitSelector
                  v-model="ruleForm.drugDosageUnit"
                  :dataList="dosageUnitList"
                >
                </UnitSelector>
                <!-- <div>
                                    {{ ruleForm.drugDosageUnit?ruleForm.drugDosageUnit:'单位'}}
                                  </div> -->
                <!-- <el-select v-model="ruleForm.drugDosageUnit" placeholder="成分"
                                    style="width: 85px;background: #fff;">
                                    <el-option v-for="item in dosageUnitList" :key="item.unitCode"
                                        :label="item.unitText" :value="item.unitCode" />
                                </el-select> -->
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <div style="position: absolute;left: 315px;top: 38px;">{{ ruleForm.drugCategory == '1' ?'x':'/' }}</div>
        <el-col :span="8">
          <el-form-item prop="minPackQty">
            <template #label>
              <div style="white-space: normal">最小包装数量丨单位</div>
            </template>
            <el-input
              v-model="ruleForm.minPackQty"
              class="inputpadding0"
              placeholder="最小包装数量"
            >
              <template #append>
                <UnitSelector
                  v-model="ruleForm.minPackUnit"
                  :dataList="minPackUnitList"
                >
                </UnitSelector>
                <!-- <el-select v-model="ruleForm.minPackUnit" placeholder="单位"
                                    style="width: 85px;    background: #fff;">
                                    <el-option v-for="item in minPackUnitList" :key="item.unitCode"
                                        :label="item.unitText" :value="item.unitCode" />
                                </el-select> -->
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <div style="position: absolute;left: 648px;top: 38px;" v-if="ruleForm.drugCategory == '1' ">/</div>
        <el-col :span="8">
          <el-form-item prop="packUnit">
            <template #label>
              <div style="white-space: normal">包装单位</div>
            </template>
            <el-select
              v-model="ruleForm.packUnit"
              filterable
              clearable
              style="width: 100%"
              placeholder="包装单位"
            >
              <el-option
                v-for="item in packUnitList"
                :key="item.unitCode"
                :label="item.unitText"
                :value="item.unitCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <div>
      <FormTitle>销售</FormTitle>
      <el-row style="margin-top: 15px">
        <el-col :span="8">
          
          <el-form-item prop="price">
            <template #label>
              <div style="white-space: normal">售价</div>
            </template>
            <el-input
              v-model="ruleForm.price"
              placeholder="售价"
              style="width: 100%"
            >
              <template #append :key="ruleForm.packUnit">
                元/{{ packUnitNameFun(ruleForm.packUnit) }} 
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '3'"
        >
          <el-form-item v-if="ruleForm.isSplit == '1'" prop="splitPrice">
            <template #label>
              <div style="white-space: normal">是否允许拆零销售</div>
            </template>
            <el-input v-model="ruleForm.splitPrice" placeholder="">
              <template #prepend>
                <el-select
                  v-model="ruleForm.isSplit"
                  placeholder=""
                  class="icon-left"
                  style="width: 97px; background: #fff"
                >
                  <el-option
                    v-for="item in YesOrNoEnum"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value"
                  />
                </el-select>
              </template>
              <template #append>
                元/{{ packUnitNameFun(ruleForm.minPackUnit) }}
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-else prop="">
            <template #label>
              <div style="white-space: normal">是否允许拆零销售</div>
            </template>
            <el-input v-model="ruleForm.splitPrice" disabled placeholder="">
              <template #prepend>
                <el-select
                  v-model="ruleForm.isSplit"
                  placeholder=""
                  class="icon-left"
                  style="width: 97px; background: #fff"
                >
                  <el-option
                    v-for="item in YesOrNoEnum"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value"
                  />
                </el-select>
              </template>
              <template #append>
                元/{{ packUnitNameFun(ruleForm.minPackUnit) }}
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '3'"
        >
          <el-form-item prop="name">
            <template #label>
              <div style="white-space: normal">库存预警数量</div>
            </template>
            <el-input
              v-model="ruleForm.stockWarningQty"
              placeholder="库存预警数量"
              style="width: 100%"
            >
              <template #append>
                {{ packUnitNameFun(ruleForm.packUnit) }}
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="ruleForm.drugCategory == '1'">
          <el-form-item prop="isMinSplit">
            <template #label>
              <div style="white-space: normal">是否允许最小单位拆分</div>
            </template>
            <el-select
              v-model="ruleForm.isMinSplit"
              clearable
              style="width: 100%"
              placeholder="是否允许最小单位拆分"
            >
              <el-option
                v-for="item in YesOrNoEnum"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <div class="table-components" v-if="ruleForm.drugCategory == '1'">
      <FormTitle>用法</FormTitle>
      <el-button style="margin: 10px 0" type="primary" @click="addUsageList"
        >加一组</el-button
      >
      <el-table
        :data="ruleForm.usageList"
        border
        style="width: 100%"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        header-cell-class-name="heardClassName"
      >
        <el-table-column prop="usageCode" label="用途" width="135">
          <template #default="scope">
            <!-- <el-select v-model="scope.row.usageCode" filterable clearable style="width:100%;" placeholder="用途">
                            <el-option v-for="item in RxTypeEnum" :key="item.usageCode" :label="item.usageName"
                                :value="item.usageCode" />
                        </el-select> -->
            <el-popover placement="right" ref="popoverRef" :popper-style="{ padding: '0' }" class="popover-RxTypeEnum" :width="380">
              <template #reference>
                <div class="btn-text">
                  {{
                    scope.row.usageCode
                      ? RxTypeEnum.find(
                          (item: any) => item.usageCode === scope.row.usageCode
                        )?.usageName
                      : '用途'
                  }}
                </div>
              </template>
              <div
                class="popover-content"
                style="
                  background: #ffffff;
                  box-shadow: 0px 12px 32px 0px rgba(0, 0, 0, 0.2);
                  border-radius: 6px 6px 6px 6px;
                  border: 1px solid #d9d9d9;
                  padding: 2px;
                  
                "
              >
                <div
                  v-for="item in RxTypeEnum"
                  :key="item.usageCode"
                  class="popover-item"
                  style="
                    width: calc(25% - 4px);
                    height: 36px;
                    background: #ffffff;
                    border-radius: 6px 6px 6px 6px;
                    display: inline-block; cursor: pointer;   line-height: 36px;margin:2px;
                    text-align: center;
                  "
                  :style="scope.row.usageCode === item.usageCode ? 'background: rgba(222, 244, 243, 1)' : ''"
                  @click="RxTypeEnumClick(item, scope.row)"
                >
                  {{ item.usageName }}
                </div>
              </div>
            </el-popover>
            <!-- <UnitSelector2  v-model="scope.row.usageCode" :dataList="RxTypeEnum">
                          </UnitSelector2> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="usageCode"
          label="每次最小用量(50kg)"
          width="110"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.singleMin"
              style="width: 50px; margin-right: 5px"
            ></el-input
            >{{ packUnitNameFun(ruleForm.minPackUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="usageCode"
          label="每次最大用量(50kg)"
          width="110"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.singleMax"
              style="width: 50px; margin-right: 5px"
            ></el-input
            >{{ packUnitNameFun(ruleForm.minPackUnit) }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="usageCode"
          label="每日最小用量(50kg)"
          width="110"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.dailyMin"
              style="width: 50px; margin-right: 5px"
            ></el-input
            >{{ packUnitNameFun(ruleForm.minPackUnit) }}
          </template>
        </el-table-column> -->
        <el-table-column
          prop="usageCode"
          label="每日最大用量(50kg)"
          width="110"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.dailyMax"
              style="width: 50px; margin-right: 5px"
            ></el-input
            >{{ packUnitNameFun(ruleForm.minPackUnit) }}
          </template>
        </el-table-column>
        <el-table-column prop="usageCode" label="最小适用年龄">
          <template #default="scope">
            <el-input
              v-model="scope.row.minAgeYear"
              style="width: 50px; margin-right: 5px"
            ></el-input
            >岁
            <el-input
              v-model="scope.row.minAgeMonth"
              style="width: 50px; margin-left: 5px; margin-right: 5px"
            ></el-input
            >月
          </template>
        </el-table-column>
        <el-table-column prop="usageCode" label="最大适用年龄">
          <template #default="scope">
            <el-input
              v-model="scope.row.maxAgeYear"
              style="width: 50px; margin-right: 5px"
            ></el-input
            >岁
            <el-input
              v-model="scope.row.maxAgeMonth"
              style="width: 50px; margin-right: 5px; margin-left: 5px"
            ></el-input
            >月
          </template>
        </el-table-column>

        <el-table-column prop="address" label="操作" width="80">
          <template #default="scope">
            <el-button
              type="text"
              style="color: #d90000"
              @click="usageListDel(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '2'">
      <FormTitle>禁止用药</FormTitle>
      <div style="margin-top: 20px; margin-bottom: 10px">
        <el-tag
          v-for="(tag, index) in conflictsList"
          @close="handleClose(index)"
          :key="tag"
          closable
          style="margin-right: 10px"
          :type="'info'"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-model="conflicts"
          v-if="conflictsList.length < 5"
          placeholder="输入并按回车创建"
          size="small"
          style="width: 110px; margin-left: 10px"
          @keyup.enter="changeConflicts(conflicts)"
        ></el-input>
      </div>
    </div>
    <div v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '2'">
      <FormTitle>推荐用药</FormTitle>
      <div style="margin-top: 20px; margin-bottom: 10px">
        <el-tag
          v-for="(tag, index) in recomsList"
          @close="handleClose2(index)"
          :key="tag"
          closable
          style="margin-right: 10px"
          :type="'info'"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-model="recoms"
          placeholder="输入并按回车创建"
          size="small"
          v-if="recomsList.length < 5"
          style="width: 110px; margin-left: 10px"
          @keyup.enter="changeRecoms(recoms)"
        ></el-input>
      </div>
    </div>
    <div v-if="ruleForm.drugCategory == '1' || ruleForm.drugCategory == '3'">
      <FormTitle>医嘱备注</FormTitle>
      <div style="margin-top: 20px; margin-bottom: 10px">
        <el-tag
          v-for="(tag, index) in instrsList"
          @close="handleClose3(index)"
          :key="tag"
          closable
          style="margin-right: 10px"
          :type="'info'"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-model="instrs"
          placeholder="输入并按回车创建"
          v-if="instrsList.length < 5"
          size="small"
          style="width: 110px; margin-left: 10px"
          @keyup.enter="changeInstrs(instrs)"
        ></el-input>
      </div>
    </div>
    <!-- <el-form-item prop="mfrId">
      <el-button
        type="primary"
        style="margin-left: auto"
        @click="handleSubmit()"
        >保存</el-button
      >
    </el-form-item> -->
  </el-form>
</template>

<script setup lang="ts">
import stores from '@/store';
import type {
  DrugInfo,
  DrugResponse,
  DrugTable,
  DrugForm,
  Profileadd,
  ProfileInfo,
} from '@/types/drug';
import type { FormRules, ElTree } from 'element-plus';
import { getMfrList } from '@/api/mfr/index';
import { getMfrSelectList } from '@/api/account';
import {
  getDrugProfileList,
  addProfile,
  updateProfile,
  deleteProfile,
  enableProfile,
  disableProfile,
} from '@/api/drug';

const formBox = ref<boolean>(true);

const popoverRef = ref<any>();

const RxTypeEnumClick = (item: any, row: any) => {
  row.usageCode = item.usageCode;
  //关闭弹窗
  popoverRef.value?.hide();
};

const mfrList = ref<any[]>([]);

const getMfrSelectListApi = async () => {
  const res = await getMfrSelectList();
  if (res.code != '200') {
    //ElMessage.error(res.msg);
  } else {
    mfrList.value = res.data || [];
  }
};
getMfrSelectListApi();

const ruleForm = ref<Profileadd>({
  drugCategory: '',
  genericName: '',
  approvalNumber: '',
  drugIngr: '',
  dosageForm: '',
  mfrId: '',
  drugDosageUnit: '',
  drugDosage: '',
  minPackQty: '',
  drugName: '',
  minPackUnit: '',
  packUnit: '',
  price: '',
  stockWarningQty: '',
  isMinSplit: '',
  splitPrice: '0',
  isSplit: 0,
  usageList: [
    {
      usageCode: '',
      singleMin: '',
      singleMax: '',
      dailyMin: '',
      dailyMax: '',
      minAgeYear: '',
      minAgeMonth: '',
      maxAgeYear: '',
      maxAgeMonth: '',
    },
  ],
  conflicts: '',
  recoms: '',
  instrs: '',
});

const conflictsList = ref<any>([]);
const conflicts = ref<string>();

//禁止用药
const changeConflicts = (e: any) => {
  //console.log(e, 'e');
  if (e != '' && e != null && e != undefined) {
    conflictsList.value.push(e);
    conflicts.value = '';
  }
};
const handleClose = (index: number) => {
  conflictsList.value.splice(index, 1);
};

//成分
const drugIngrList = ref<any>([]);

//推荐用药;
const recomsList = ref<any>([]);
const recoms = ref<string>();
const changeRecoms = (e: any) => {
  //console.log(e);

  if (e != '' && e != null && e != undefined) {
    recomsList.value.push(e);
    recoms.value = '';
  }
};
const handleClose2 = (index: number) => {
  recomsList.value.splice(index, 1);
};

//医嘱;
const instrsList = ref<any>([]);
const instrs = ref<string>();

const changeInstrs = (e: any) => {
  if (e != '' && e != null && e != undefined) {
    instrsList.value.push(e);
    instrs.value = '';
  }
};
const handleClose3 = (index: number) => {
  instrsList.value.splice(index, 1);
};

//删除用法

const usageListDel = (index: number) => {
  ruleForm.value.usageList?.splice(index, 1);
};

///药品分类;成药，中药，耗材
const btnList = ref<any>(
  stores.useBaseDataStore().getEnumSelect('drugCategoryEnum')
);
//药品成分
const DRUG_INGR = ref<any>(
  stores.useBaseDataStore().getDictsSelect('DRUG_INGR')
);

//剂型
const DosageFormEnum = ref<any>(
  stores.useBaseDataStore().getEnumSelect('dosageFormEnum')
);

//是否允许拆零销售
const YesOrNoEnum = ref<any>(
  stores.useBaseDataStore().getEnumSelect('yesOrNoEnum')
);

//用途
const RxTypeEnum = ref<any>([]);
const USAGE = ref<any>(stores.useBaseDataStore().getDictsSelect('USAGE'));
RxTypeEnum.value = USAGE.value;

const dosageUnit = ref<any>(stores.useBaseDataStore().getDictsSelect('UNIT'));
const dosageUnitList = ref<any>();
const packUnitList = ref<any>();
const minPackUnitList = ref<any>();
//剂量单位;g
dosageUnitList.value = dosageUnit.value.filter(
  (item: { unitType: number }) => item.unitType == 3
);
//包装单位
packUnitList.value = dosageUnit.value.filter(
  (item: { unitType: number }) => item.unitType == 1
);

//最小包装单位
minPackUnitList.value = dosageUnit.value.filter(
  (item: { unitType: number }) => item.unitType == 1
);
// ruleForm.value.minPackUnit = minPackUnitList.value[0].unitCode

let rules = reactive<FormRules<any>>({
  drugName: [{ required: true, message: '请输入药品名', trigger: 'blur' }],
  genericName: [{ required: true, message: '请输入通用名', trigger: 'blur' }],
  drugDosage: [
    { required: true, message: '请输入剂量（成分含量）', trigger: 'blur' },
  ],
  minPackQty: [
    { required: true, message: '请输入最小包装数量', trigger: 'blur' },
  ],
  packUnit: [{ required: true, message: '请选择包装单位', trigger: 'change' }],
  price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
  splitPrice: [{ required: true, message: '请输入零销售价', trigger: 'blur' }],
  isMinSplit: [
    {
      required: true,
      message: '请选择是否允许最小单位拆分',
      trigger: 'change',
    },
  ],
});

const packUnitNameFun = (row: any) => {
  for (let index = 0; index < packUnitList.value.length; index++) {
    let item = packUnitList.value[index];
    if (item.unitCode == row) {
      return item.unitText;
    }
  }
};

//加一组

const addUsageList = () => {
  ruleForm.value.usageList?.push({
    usageCode: '',
    singleMin: '',
    singleMax: '',
    dailyMin: '',
    dailyMax: '',
    minAgeYear: '',
    minAgeMonth: '',
    maxAgeYear: '',
    maxAgeMonth: '',
  });
};

const addProfileApi = async () => {
  let data:any = {};
  //ruleForm.value
  if (ruleForm.value.drugCategory == '1') {
    data = JSON.parse(JSON.stringify(ruleForm.value));
  }
  if (ruleForm.value.drugCategory == '2') {
    data = {
      drugCategory: ruleForm.value.drugCategory,
      drugName: ruleForm.value.drugName,
      genericName: ruleForm.value.genericName,
      dosageForm: ruleForm.value.dosageForm,
      mfrId: ruleForm.value.mfrId,
      price: ruleForm.value.price,
      ruleForm: ruleForm.value.packUnit,
      conflicts: ruleForm.value.conflicts,
      recoms: ruleForm.value.recoms,
    };
  }
  if (ruleForm.value.drugCategory == '3') {
    data = {
      drugCategory: ruleForm.value.drugCategory,
      drugName: ruleForm.value.drugName,
      genericName: ruleForm.value.genericName,
      approvalNumber: ruleForm.value.approvalNumber,
      mfrId: ruleForm.value.mfrId,
      minPackQty: ruleForm.value.minPackQty,
      minPackUnit: ruleForm.value.minPackUnit,
      packUnit: ruleForm.value.packUnit,
      price: ruleForm.value.price,
      isSplit: ruleForm.value.isSplit,
      splitPrice: ruleForm.value.splitPrice,
      stockWarningQty: ruleForm.value.stockWarningQty,
      instrs: ruleForm.value.instrs,
    };
  }

  if (ruleForm.value.price) {
    data.price =  Number((ruleForm.value.price * 100).toFixed(2));
  }
  if (ruleForm.value.splitPrice) {
    data.splitPrice =  Number((ruleForm.value.splitPrice * 100).toFixed(2));
  }
  let res = await addProfile(data);
  if (res.code == '200') {
    ElMessage({
      type: 'success',
      message: res.msg,
    });
    closeDrawer();
  } else {
    // ElMessage({
    //   type: 'warning',
    //   message: res.msg,
    // });
  }
};

const updateProfileApi = async () => {
  
  let data:any = JSON.parse(JSON.stringify(ruleForm.value));
  if (ruleForm.value.price) {
    data.price =  Number((ruleForm.value.price * 100).toFixed(2));
  }
  if (ruleForm.value.splitPrice) {
    data.splitPrice =  Number((ruleForm.value.splitPrice * 100).toFixed(2));
  }
  let res = await updateProfile(data);
  if (res.code == '200') {
    ElMessage({
      type: 'success',
      message: res.msg,
    });
    closeDrawer();
  } else {
    // ElMessage({
    //   type: 'warning',
    //   message: res.msg,
    // });
  }
};
const dataType = defineProps<{ dataType: Number; dataInfos: Profileadd }>();

const ruleFormRef = ref();
defineExpose<{
  open: () => void;
}>({
  open() {
    handleSubmit();
  },
});
const handleSubmit = async () => {
  ruleForm.value.conflicts = conflictsList.value.join(',');
  ruleForm.value.recoms = recomsList.value.join(',');
  ruleForm.value.instrs = instrsList.value.join(',');
  ruleForm.value.drugIngr = drugIngrList.value.join(',');

  
  let list: any[] = [];
  if (ruleForm.value?.usageList) {
    for (let index = 0; index < ruleForm.value?.usageList.length; index++) {
      let item = ruleForm.value.usageList[index];
      if (item?.usageCode != '') {
        list.push(item);
      }
    }
  }

  ruleForm.value.usageList = list;
  const form = ruleFormRef.value;
  await form.validate((valid: any, fields: any) => {
    if (valid) {
      if (dataType.dataType === 0) {
        addProfileApi();
      } else {
        updateProfileApi();
      }
    } else {
      //console.log('error submit!', fields);
    }
  });
};

ruleForm.value = dataType.dataInfos;
if (dataType.dataInfos.conflicts)
  conflictsList.value = dataType.dataInfos.conflicts?.split(',');
if (dataType.dataInfos.instrs)
  instrsList.value = dataType.dataInfos.instrs?.split(',');
if (dataType.dataInfos.recoms)
  recomsList.value = dataType.dataInfos.recoms?.split(',');
if (dataType.dataInfos.drugIngr)
  drugIngrList.value = dataType.dataInfos.drugIngr?.split(',');

if (!ruleForm.value.drugCategory) {
  ruleForm.value.drugCategory = btnList.value[0].value;
}
if (!ruleForm.value.minPackUnit) {
  ruleForm.value.minPackUnit = minPackUnitList.value[0].unitCode;
}
if (!ruleForm.value.packUnit) {
  ruleForm.value.packUnit = packUnitList.value[0].unitCode;
}
if (!ruleForm.value.drugDosageUnit) {
  ruleForm.value.drugDosageUnit = dosageUnitList.value[0].unitCode;
}

const selectRules = () => {
  //西药
  formBox.value = false;
  if (ruleForm.value.drugCategory == '1') {
    rules = reactive<FormRules<any>>({
      drugName: [{ required: true, message: '请输入药品名', trigger: 'blur' }],
      genericName: [
        { required: true, message: '请输入通用名', trigger: 'blur' },
      ],
      drugDosage: [
        { required: true, message: '请输入剂量（成分含量）', trigger: 'blur' },
      ],
      minPackQty: [
        { required: true, message: '请输入最小包装数量', trigger: 'blur' },
      ],
      packUnit: [
        { required: true, message: '请选择包装单位', trigger: 'change' },
      ],
      price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
      splitPrice: [
        { required: true, message: '请输入零销售价', trigger: 'blur' },
      ],
      isMinSplit: [
        {
          required: true,
          message: '请选择是否允许最小单位拆分',
          trigger: 'change',
        },
      ],
    });
    packUnitList.value = dosageUnit.value.filter(
      (item: { unitType: number }) => item.unitType == 1
    );
    ruleForm.value.packUnit = ruleForm.value.packUnit == '' ?'G1':ruleForm.value.packUnit;
  }
  //中药
  if (ruleForm.value.drugCategory == '2') {
    rules = reactive<FormRules<any>>({
      drugName: [{ required: true, message: '请输入药品名', trigger: 'blur' }],
      price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
      genericName: [
        { required: true, message: '请输入通用名', trigger: 'blur' },
      ],
    });
    packUnitList.value = dosageUnit.value.filter(
      (item: { unitType: number }) => item.unitType == 1
    );
    ruleForm.value.packUnit = 'G1';
    
  }
  if (ruleForm.value.drugCategory == '3') {
    rules = reactive<FormRules<any>>({
      drugName: [{ required: true, message: '请输入耗材名', trigger: 'blur' }],
      genericName: [
        { required: true, message: '请输入通用名', trigger: 'blur' },
      ],

      minPackQty: [
        { required: true, message: '请输入最小包装数量', trigger: 'blur' },
      ],
      packUnit: [
        { required: true, message: '请选择包装单位', trigger: 'change' },
      ],
      price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
      // splitPrice: [
      //     { required: true, message: '请输入零销售价', trigger: 'blur' },
      // ],
      isMinSplit: [
        {
          required: true,
          message: '请选择是否允许最小单位拆分',
          trigger: 'change',
        },
      ],
    });

    packUnitList.value = dosageUnit.value.filter(
      (item: { unitType: number }) => item.unitType == 1
    );
    ruleForm.value.packUnit = ruleForm.value.packUnit == '' ?'G1':ruleForm.value.packUnit;
  }
  setTimeout(() => {
    formBox.value = true;
  }, 200);
};

const emit = defineEmits(['closeDrawer']);
const closeDrawer = () => {
  emit('closeDrawer');
};
</script>
<style lang="scss">
.form1-ruleForm .el-form-item {
  display: block !important;
}
.form1-ruleForm .el-table .cell {
  font-size: 12px;
}
.inputpadding0 {
  .el-input-group__append {
    padding: 0 !important;
  }
}
 .table-components .btn-text {
  font-size: 12px;
  padding: 4px 20px;
  background: rgba(227, 227, 227, 0.1);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #ebebeb;
}
.form1-ruleForm .table-components .el-table td.el-table__cell div {
  background: rgba(227, 227, 227, 0.1);
}
</style>
<style lang="scss" scoped>
:deep(.el-popover) {
  padding: 0px;
}
:deep(.popover-content div) {
  div {
  }
}
</style>
